//
//  StatusPictureView.swift
//  SinaWeibo
//
//  Created by 小果 on 16/2/14.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit
import SDWebImage
//MARK: - 通知的常量(常量是保存在常量区的，所有的常量是共享的，一定要足够的长，这样可以避免重复)
// 选中照片的通知
let XGStatusPictureViewSelectPhotoNotification = "XGStatusPictureViewSelectPhotoNotification"
// 选中的图片的索引对应的key
let XGStatusPictureViewSelectPhotoIndexPahtKey = "XGStatusPictureViewSelectPhotoIndexPahtKey"
// 选中的图片的URL对应的Key
let XGStatusPictureViewSelectPhotoURLsKey = "XGStatusPictureViewSelectPhotoUrlsKey"
/// 可重用的cell的标识符
private let XGStatusPictureViewCellID = "StatusPictureViewCellID"

class StatusPictureView: UICollectionView {
    /// 微博的配图视图模型
    var statusViewModel: StatusViewModel? {
        didSet{
            sizeToFit()
            // 刷新数据
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calViewSize()
    }
    
    ///  根据模型中的图片数量来计算视图的大小
    private func calViewSize() -> CGSize {
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        /// 设置默认大小
        layout.itemSize = CGSize(width: XGStatusPictureItemWH, height: XGStatusPictureItemWH)
        
        /// 根据图片数量来计算大小
        let count = statusViewModel?.thumbnailURLs?.count ?? 0
        // 没有配图
        if count == 0 {
            return CGSizeZero
        }
        // 有一张配图
        if count == 1 {
            
            var size = CGSize(width: 150, height: 150)
            // 判断图片是否已经被正确缓存，key是URL的完整字符串
            let key = statusViewModel?.thumbnailURLs![0].absoluteString
            // 如果有缓存图片，就记录当前缓存图片的大小
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
              size = image.size
            }
            
            // 单独处理过宽或者过窄的图片
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > 300 ? 300 : size.width
            
            layout.itemSize = size
            return size
        }
        // 有4张配图
        if count == 4 {
            let w = 2 * XGStatusPictureItemWH + XGStatusPictureItemMargin
            return CGSize(width: w, height: w)
        }
        // 其他
        let row = CGFloat((count - 1) / Int(XGStatusPictureMaxCount) + 1)
        let h = row * XGStatusPictureItemWH + (row - 1) * XGStatusPictureItemMargin
        let w = XGStatusPictureMaxWidth
    
        return CGSize(width: w, height: h)
    }
        
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
//        backgroundColor = UIColor.lightGrayColor()
        backgroundColor = UIColor.whiteColor()
        
        // 设置布局的间距
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = XGStatusPictureItemMargin
        layout.minimumLineSpacing = XGStatusPictureItemMargin
        
        // 指定数据源和代理
        dataSource = self
        delegate = self
        // 注册可重用的cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: XGStatusPictureViewCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - collectionView的数据源方法
extension StatusPictureView : UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 测试起始位置和目标位置
//        let v = UIView(frame: fullScreenRect(indexPath))
////        v.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
                
        // 发送通知
        /**
            object:发送的对象，可以传递一个数值，也可以是‘自己’，通过obj.属性
            userInfo:可选字典，可以传递多个数值
        */
        NSNotificationCenter.defaultCenter().postNotificationName(XGStatusPictureViewSelectPhotoNotification, object: self, userInfo: [XGStatusPictureViewSelectPhotoIndexPahtKey: indexPath, XGStatusPictureViewSelectPhotoURLsKey: (statusViewModel!.bmiddleURLs)!])
    }
    // 返回指定的indexPath对应的cell在屏幕上的坐标的位置
    func screenRect(indexPath: NSIndexPath) -> CGRect {
        // 跟踪用户的点击位置
        let cell = cellForItemAtIndexPath(indexPath)
   
        // 将用户点击的cell的坐标进行转换
        return convertRect(cell!.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    // 返回指定的indexPath对应的图片完全的放大后，在屏幕上对应的坐标
    func fullScreenRect(indexPath: NSIndexPath) -> CGRect {
        // 根据‘缩略图’的图片来计算目标的尺寸
        // 1、拿到缩略图
        let key = statusViewModel?.thumbnailURLs![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        // 2、根据图片来计算宽高比
        let scale = image.size.height / image.size.width
        let w = UIScreen.mainScreen().bounds.width
        let h = w * scale
        
        // 3、判断高度
        var y = (UIScreen.mainScreen().bounds.height - h) * 0.5
        
        if y < 0 { // 如果图片的高度大于屏幕的高度，就让图片的Y值为0
            y = 0
        }
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XGStatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = statusViewModel!.thumbnailURLs![indexPath.item]
        
        return cell
    }
}


///  配图的cell
private class StatusPictureViewCell: UICollectionViewCell {
    
    // 配图视图的URL
    var imageURL: NSURL? {
        didSet{
            iconView.sd_setImageWithURL(imageURL)
            
            // 在设置图像URL的同时，根据图片的扩展名来判断是否是GIF动图
            gifIconView.hidden = ((imageURL!.absoluteString) as NSString).pathExtension.lowercaseString != "gif"
        }
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(iconView)
        iconView.addSubview(gifIconView)
        
        iconView.ff_Fill(self)
        gifIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载
    private lazy var iconView: UIImageView = {
        let icon = UIImageView()
        // 设置填充模式
        icon.contentMode = UIViewContentMode.ScaleAspectFill
        icon.clipsToBounds = true
    
    return icon
    }()
    // gif 动态图片提示
    private lazy var gifIconView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}


